package com.gitee.wsl.platform.thread.task.api

import com.gitee.wsl.platform.concurrent.api.Cancellable
import com.gitee.wsl.platform.thread.task.bean.Task


/**
 * Represents a delayed computation (a thunk).
 *
 *
 * These functions are allowed to trigger side effects, with
 * blocking I/O and to throw exceptions.
 */
fun interface DelayedFun<T> {
    @Throws(Exception::class)
    fun invoke(): T
}

fun <T > DelayedFun<out T>.taskUninterruptibleBlockingIO(): Task<T> {
    val func = this
    return Task.fromAsync(AsyncFun{ ec, callback ->
        try {
            callback.onSuccess(func.invoke())
        } catch (e: InterruptedException) {
            callback.onCancellation()
        } catch (e: Exception) {
            callback.onFailure(e)
        }
        Cancellable {}
    })
}